package com.zzyl.service.customer.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.VisitDto;
import com.zzyl.entity.Visit;
import com.zzyl.mapper.customer.ReservationMapper;
import com.zzyl.service.customer.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.TimeCountVo;
import com.zzyl.vo.VisitVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Description reservationServiceImpl
 * @Author liangDong
 * @Date 2025-05-16  12:07
 */
@Service
@Slf4j
public class ReservationServiceImpl implements ReservationService {
    @Autowired
    private ReservationMapper reservationMapper;


    private static Integer count = 0;

    @Override
    public Integer getCancelledCount(){
        return count;
    }

    @Override
    public PageResponse<VisitVo> page(int status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Long userId = UserThreadLocal.getUserId();
        Page<Visit> vos = reservationMapper.selelctAll(status,userId);
        PageResponse<VisitVo> visitVoList = PageResponse.of(vos,VisitVo.class);
        return visitVoList;
    }

    @Override
    public void add(VisitDto visitDto) {
        Visit visit = BeanUtil.toBean(visitDto, Visit.class);
        visit.setStatus(0);
        visit.setCreateBy(UserThreadLocal.getUserId());
        visit.setCreateTime(LocalDateTime.now());
        reservationMapper.insert(visit);
    }

    @Override
    public void cancel(Long id) {
        Integer status = 2;
        count++;
        reservationMapper.cancel(id,status);
    }

    public void clearCancelledCount(){
        log.info("把每天的取消预约次数清零:{}", LocalDateTime.now());
        count=0;
    }

    @Override
    public List<TimeCountVo> getCountList(Long time) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
        // 定义日期格式化模板
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化为字符串
        String formattedTime = localDateTime.format(formatter);


        Long id = UserThreadLocal.getUserId();
        List<TimeCountVo> countList = reservationMapper.getCountList(formattedTime,id);
        return countList;
    }


}
